import { ContainerModule } from 'inversify';
import {
    bindViewContribution,
    WidgetFactory
} from '@theia/core/lib/browser';
import {  CommandContribution } from '@theia/core/lib/common';
import {  FrontendApplicationContribution } from '@theia/core/lib/browser';
import { ToolsWidget } from './tools-widget';
import { WebviewWidget } from './webview-widget';
import {
    ToolsViewContribution,
    ToolsCommandContribution,
} from './tools-contribution';
import { TOOLS_WIDGET_FACTORY_ID, WEBVIEW_WIDGET_FACTORY_ID } from '../common/tools-types';
// 导入样式
import './style/tools.css';

export default new ContainerModule(bind => {
    console.log('Loading tools frontend module...');

    try {
        // 绑定工具集Widget
        bind(ToolsWidget).toSelf().inSingletonScope();

        bind(WidgetFactory).toDynamicValue(ctx => ({
                id: TOOLS_WIDGET_FACTORY_ID,
                createWidget: async (options?: any) => {
                    const container = ctx.container; // ✅ 从上下文获取 container
                    const widget = container.get<ToolsWidget>(ToolsWidget);

                    widget.id = options?.id || TOOLS_WIDGET_FACTORY_ID;
                    return widget;
                }
        })).inSingletonScope();

        // 绑定Webview Widget
        console.log('Binding WebviewWidget...');
        // 绑定 WebviewWidget
        bind(WebviewWidget).toSelf().inTransientScope(); // 或 inTransientScope()

        // 绑定工厂
        bind(WidgetFactory).toDynamicValue(ctx => ({
                id: WebviewWidget.FACTORY_ID,
                createWidget: async (options?: any) => {
                        // ✅ 使用 ctx.container.get() 创建实例，触发 @inject 和 @postConstruct
                         console.log('[Factory] Creating NEW WebviewWidget', options?.id);
                         const widget = ctx.container.get<WebviewWidget>(WebviewWidget);
                        // 设置 ID
                            if (options?.id) {
                                    widget.id = options.id;
                             } else {
                                    widget.id = WebviewWidget.FACTORY_ID;
                            }

                            return widget;
                },
        })).inSingletonScope();
        // 绑定视图贡献
        bindViewContribution(bind, ToolsViewContribution);

        // 绑定前端应用贡献
        bind(FrontendApplicationContribution).toService(ToolsViewContribution);

        // 绑定命令贡献
        bind(CommandContribution).to(ToolsCommandContribution).inSingletonScope();


    } catch (error) {
        console.error('Error loading tools frontend module:', error);
        throw error;
    }
});